package cn.tedu.smartos.family_user.service.impl;

import cn.tedu.smartos.base.exception.ServiceException;
import cn.tedu.smartos.base.response.StatusCode;
import cn.tedu.smartos.family_user.mapper.MedicationReminderMapper;
import cn.tedu.smartos.family_user.pojo.dto.MedicationReminderAddParam;
import cn.tedu.smartos.family_user.pojo.dto.MedicationReminderUpdateParam;
import cn.tedu.smartos.family_user.pojo.entity.MedicationReminder;
import cn.tedu.smartos.family_user.pojo.vo.MedicationReminderVO;
import cn.tedu.smartos.family_user.service.MedicationReminderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class MedicationReminderServiceImpl implements MedicationReminderService {

    @Autowired
    private MedicationReminderMapper medicationReminderMapper;

    @Override
    @Transactional
    public Long addMedicationReminder(MedicationReminderAddParam addParam) {
        MedicationReminder reminder = new MedicationReminder();
        BeanUtils.copyProperties(addParam, reminder);
        reminder.setCreateTime(new Date());
        reminder.setUpdateTime(new Date());
        reminder.setIsActive(1); // 默认激活

        medicationReminderMapper.insert(reminder);
        return reminder.getReminderId();
    }

    @Override
    @Transactional
    public void updateMedicationReminder(MedicationReminderUpdateParam updateParam) {
        MedicationReminderVO existingVo = medicationReminderMapper.findById(updateParam.getReminderId());
        if (existingVo == null) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "用药提醒不存在");
        }

        MedicationReminder reminder = new MedicationReminder();
        BeanUtils.copyProperties(updateParam, reminder);
        reminder.setUpdateTime(new Date());

        medicationReminderMapper.update(reminder);
    }

    @Override
    @Transactional
    public void deleteMedicationReminder(Long reminderId) {
        int rows = medicationReminderMapper.deleteById(reminderId);
        if (rows != 1) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "删除用药提醒失败");
        }
    }

    @Override
    public MedicationReminderVO getMedicationReminderById(Long reminderId) {
        MedicationReminderVO vo = medicationReminderMapper.findById(reminderId);
        if (vo == null) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "用药提醒不存在");
        }
        return vo;
    }

    @Override
    public List<MedicationReminderVO> listMedicationRemindersByElderly(Long elderlyUserId) {
        return medicationReminderMapper.findByElderlyUserId(elderlyUserId);
    }

    @Override
    @Transactional
    public void toggleReminderStatus(Long reminderId, Integer isActive) {
        if (isActive != 0 && isActive != 1) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "无效的状态值");
        }

        int rows = medicationReminderMapper.updateActiveStatus(reminderId, isActive);
        if (rows != 1) {
            throw new ServiceException(StatusCode.INVALID_REQUEST, "更新提醒状态失败");
        }
    }

    // 每分钟检查一次需要发送的提醒
    @Scheduled(cron = "0 * * * * ?")
    @Override
    public void checkAndSendReminders() {
        log.debug("开始执行用药提醒检查任务...");

        // 获取当前时间(HH:mm格式)
        String currentTime = getCurrentTimeFormatted();

        // 获取当前星期几(1=周一, 2=周二, ..., 7=周日)
        int dayOfWeek = getCurrentDayOfWeek();

        // 查询需要发送的提醒
        List<MedicationReminder> reminders = medicationReminderMapper
                .findActiveRemindersForTime(currentTime, dayOfWeek);

        if (!reminders.isEmpty()) {
            log.info("找到 {} 个需要发送的用药提醒", reminders.size());
            for (MedicationReminder reminder : reminders) {
                sendMedicationReminder(reminder);
            }
        }
    }

    private void sendMedicationReminder(MedicationReminder reminder) {
        // 这里实现实际的提醒发送逻辑
        // 可以是APP推送、短信、微信通知等
        log.info("发送用药提醒: 老人ID={}, 药品={}, 剂量={}, 时间={}, 星期={}",
                reminder.getElderlyUserId(),
                reminder.getMedicationName(),
                reminder.getDosage(),
                getCurrentTimeFormatted(),
                getCurrentDayOfWeek());

        // TODO: 实际发送提醒的实现
        // 1. 调用推送服务发送APP通知
        // 2. 调用短信服务发送短信
        // 3. 调用微信服务发送模板消息
    }

    // 获取当前时间(HH:mm格式)
    private String getCurrentTimeFormatted() {
        return new java.text.SimpleDateFormat("HH:mm").format(new Date());
    }

    // 获取当前星期几(1=周一, 2=周二, ..., 7=周日)
    private int getCurrentDayOfWeek() {
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_WEEK);

        // Calendar中: 周日=1, 周一=2, ..., 周六=7
        // 转换为: 周一=1, 周二=2, ..., 周日=7
        return day == Calendar.SUNDAY ? 7 : day - 1;
    }
    @Override
    public List<MedicationReminderVO> listAllMedicationReminders() {
        return medicationReminderMapper.findAll();
    }

    @Override
    public List<MedicationReminderVO> listMedicationRemindersByFamilyUser(Long familyUserId) {
        return medicationReminderMapper.findByFamilyUserId(familyUserId);
    }
}